package bootstrap

import (
	"encoding/json"
	"ia/apps/admin/middleware/logsink"
	"ia/common/model"
	modeladmin "ia/common/model/admin"
	"ia/common/support/global"
	"strings"
	"time"

	"github.com/kataras/iris/v12"
)

/*
 * 埋点日志
 */
func done(ctx iris.Context) {
	for _, v := range logsink.GPolicyLogList {
		if v.V2 == ctx.Path() && v.V3 == ctx.Method() {
			st := ctx.Values().GetInt64Default("st", 0)
			diff := time.Since(time.UnixMicro(st)).Milliseconds() // 毫秒 1/1000s

			params, _ := json.Marshal(ctx.URLParams())
			body, _ := ctx.GetBody()

			var groupName, name string
			routeStr := strings.Split(ctx.GetCurrentRoute().String(), " ")
			if len(routeStr) > 0 {
				title := routeStr[0]
				arr := strings.Split(title, "~")
				if len(arr) >= 2 {
					groupName = arr[0]
					name = arr[1]
				}
			}

			userAgent := ctx.Request().UserAgent()
			var userAgent2 string = "未知"
			if strings.Contains(userAgent, "Chrome") {
				userAgent2 = "Chrome"
			}
			if strings.Contains(userAgent, "Firefox") {
				userAgent2 = "Firefox"
			}
			logsink.GLogSink.Append(&modeladmin.AdminLog{
				Model: model.Model{
					CreatorId: ctx.Values().GetInt64Default(global.Uid, 0),
				},
				IpAddr:         ctx.RemoteAddr(),
				City:           ctx.RemoteAddr(),
				Os:             strings.Replace(ctx.Request().Header.Get("Sec-Ch-Ua-Platform"), "\"", "", -1),
				UserAgent:      userAgent2,
				Path:           ctx.Path(),
				Method:         ctx.Method(),
				Params:         string(params),
				Data:           string(body),
				GroupName:      groupName,
				Name:           name,
				Duration:       int(diff),
				RespStatusCode: ctx.ResponseWriter().StatusCode(),
			})
		}
	}
}
